﻿using AdvanceTeam.Main;
using PlayerRoles;
using PluginAPI.Core;
using PluginAPI.Core.Attributes;
using PluginAPI.Enums;
using PluginAPI.Events;
using System;
using Utils;



namespace AdvanceTeam.Event
{
    public class RoundStartTeamEvent
    {

        [PluginEvent(ServerEventType.RoundStart)]
        public void OnRoundStart(RoundStartEvent ev)
        {
            bool canRefresh = Player.Count >= CodeLoad.Singleton.Config.RoundStartTeamEvent.CanRefreshCount;

            if (!canRefresh)
            {
                Log.Info($"[插件|先遣队] 无法满足触发条件|要求人数：{CodeLoad.Singleton.Config.RoundStartTeamEvent.CanRefreshCount}");
                return;
            }

            TimeCoroutine.Delay(CodeLoad.Singleton.Config.RoundStartTeamEvent.Duration, () =>
            {
                if (Round.IsLocked) return;

                bool isNTF = UnityEngine.Random.Range(0f, 1f) <= CodeLoad.Singleton.Config.RoundStartTeamEvent.PercentNTF;

                RoleTypeId roleTypeId = isNTF ?
                    RoleTypeId.Scientist :
                    RoleTypeId.ClassD;

                RoleTypeId toTeam = isNTF ?
                    RoleTypeId.NtfCaptain :
                    RoleTypeId.ChaosRifleman;

                int maxCount = isNTF ?
                    CodeLoad.Singleton.Config.RoundStartTeamEvent.MaxRespawnNTF :
                    CodeLoad.Singleton.Config.RoundStartTeamEvent.MaxRespawnCI;


                if (PlayerUtils.TryGetPlayers(roleTypeId, maxCount, out Player[] output))
                {
                    Cassie.Message("这里是 <color=yellow>[快速反应小队]</color>，已确认危险求救代码 <color=red>[JSXFD-23DF]</color>。先遣小组即将行动。", true, true, true);

                    Array.ForEach(output, e =>
                    {
                        e.SetRole(toTeam, RoleChangeReason.RoundStart);
                    });
                }
            });
        }


        [PluginEvent(ServerEventType.TeamRespawn)]
        public void OnTeamRespawn(TeamRespawnEvent ev)
        {
            if (ev.Team == Respawning.SpawnableTeamType.NineTailedFox)
            {
                return;
            }

            if (ev.Team == Respawning.SpawnableTeamType.ChaosInsurgency)
            {
                TimeCoroutine.Delay(1f, () =>
                {
                    ev.Players.FindAll(e => e.Role == RoleTypeId.ChaosRifleman).ForEach(e => e.AddItem(ItemType.GunA7));
                });
            
                return;
            }
        }
    }
}
